package user.controller;



import commons.ResultBean;
import entity.CcmsCredit;
import entity.TEssential;
import entity.UserCredit;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import user.service.ICredit;
import user.service.ITEssential;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


//信用卡管理
@Controller
@RequestMapping("/credit")
public class CreditController {
    
    @Autowired
    ICredit iCredit;

    @Autowired
    ITEssential itEssential;

    //页面跳转
    @ApiOperation(value = "跳转到激活界面")
    @GetMapping("/test")
    public String test(){
        return "active";
    }

    @ApiOperation(value = "跳转到挂失界面")
    @GetMapping("/test2")
    public String test2(){
        return "guashi";
    }

    @ApiOperation(value = "跳转到冻结界面")
    @GetMapping("/test3")
    public String test3(){
        return "dongjie";
    }

    @ApiOperation(value = "跳转到注销界面")
    @GetMapping("/test4")
    public String test4(){
        return "zhuxiao";
    }

    /**
     * 修改密码查询用户所有的卡
     * @param model
     * @param request
     * @return
     */
    @ApiOperation(value = "修改密码查询用户所有的卡")
    @GetMapping(value = "/test5")
    public String test5(Model model, HttpServletRequest request){
        Integer userId =  Integer.parseInt(request.getSession().getAttribute("userid").toString());
        List<CcmsCredit> myCredits = iCredit.getMyCredit(userId);
        List<CcmsCredit> myCredit=new ArrayList<>();
        for (CcmsCredit ccs:myCredits){
            if(!ccs.getStatus().equals("已注销")){
                myCredit.add(ccs);
            }
        }
        List list=new ArrayList();
        List<CcmsCredit> list1=new ArrayList<>();
        int a=0;
        for (CcmsCredit s:myCredit) {
            list1.add(s);
            a+=1;
            if(a%2==0){
                list.add(list1);
                list1=new ArrayList<>();
            }
        }
        List<CcmsCredit> list2=new ArrayList<>();
        if(a%2==1){
            list2.add(myCredit.get(myCredit.size()-1));
            list.add(list2);
        }
        model.addAttribute("list",list);
        return "choosecard";
    }

    /**
     * 修改额度查询用户所有的卡
     * @param model
     * @param request
     * @return
     */
    @ApiOperation(value = "修改额度查询用户所有的卡")
    @GetMapping(value = "/test6")
    public String test6(Model model, HttpServletRequest request){
        Integer userId =  Integer.parseInt(request.getSession().getAttribute("userid").toString());
        List<CcmsCredit> myCredits = iCredit.getMyCredit(userId);
        List<CcmsCredit> myCredit=new ArrayList<>();
        for (CcmsCredit ccs:myCredits){
            if(!ccs.getStatus().equals("已注销")){
                myCredit.add(ccs);
            }
        }
        List list=new ArrayList();
        List<CcmsCredit> list1=new ArrayList<>();
        int a=0;
        for (CcmsCredit s:myCredit) {
            list1.add(s);
            a+=1;
            if(a%2==0){
                list.add(list1);
                list1=new ArrayList<>();
            }
        }
        List<CcmsCredit> list2=new ArrayList<>();
        if(a%2==1){
            list2.add(myCredit.get(myCredit.size()-1));
            list.add(list2);
        }
        model.addAttribute("list",list);
        return "choosecard1";
    }
    /**
     *信用卡激活功能
     *       当用户填写完证件号和信用卡号
     *       后点击激活按钮后触发
     *       返回卡片信息
     */
    @ApiOperation(value = "查询信用卡与证件号是否匹配")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "identityId",value = "证件号",required = true,dataType = "String"),
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "String")
    })
    @PostMapping(value = "/toActive")
    public String toActive(String identityId, String cardnum, Model model, HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(Long.valueOf(cardnum),request);
        TEssential ccmsUser=itEssential.getUser(identityId);
        if(ccmsCredit!=null && ccmsUser!=null) {
            if (ccmsCredit.getEssentialId() == ccmsUser.getEssentialid()) {
                UserCredit uc = new UserCredit(identityId, Long.valueOf(cardnum), ccmsUser.getRealname(), ccmsCredit.getActive());
                model.addAttribute("rb", uc);
                return "active2";
            } else {
                return null;
            }
        }else {
            return null;
        }
    }

    /**
     * 申请激活
     * @param cardnum
     * @param model
     * @return
     */
    @ApiOperation(value = "信用卡激活功能")
    @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "String")
    @PostMapping(value = "/toActive3")
    public String toActive3(String cardnum,Model model,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(Long.valueOf(cardnum),request);
        if(ccmsCredit.getActive().equals("未激活")){
            ResultBean rb=iCredit.toActive(ccmsCredit);
            if(rb!=null){
                model.addAttribute("msg",rb.getMessage());
            }else {
                model.addAttribute("msg","服务器故障，请稍后再试或联系管理员\n管理员电话：133xxxxxxxx");
            }
        }else {
            model.addAttribute("msg","操作失败，此信用卡"+ccmsCredit.getActive()+"，无法再次激活");
        }
        return "active3";
    }

    /**
     *       先验证信用卡
     *       验证手机号是否为预留手机号
     * */

    @ApiOperation(value = "信用卡激活功能")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "phonenumber",value = "手机号",required = true,dataType = "String")
    })
    @PostMapping(value = "/toguashi")
    @ResponseBody
    public ResultBean guashi(long cardnum,String phonenumber,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(cardnum,request);
        TEssential ccmsUser=itEssential.getUserByKey(ccmsCredit.getEssentialId());
        if(ccmsUser.getPhonenumber().equals(phonenumber)){
            return new ResultBean(200,"",true);
        }else {
            return new ResultBean(500,"与预留手机不符",false);
        }
    }

    /**
     *信用卡挂失(冻结，注销)：
     *       验证手机号和短信后
     *       提交申请
     **/
    @ApiOperation(value = "信用卡挂失(冻结，注销)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "type",value = "申请类型",required = true,dataType = "int")
    })
    @PostMapping(value = "/toguashi2")
    public String guashi2(long cardnum,int type,Model model,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(cardnum,request);
    //type 1正常使用 2 代表挂失中,3代表已挂失，4代表申请冻结，5代表已冻结，6代表申请注销，7已注销
        if(ccmsCredit.getStatus().equals("正常")){
            ResultBean rb=iCredit.updateStatus(ccmsCredit,type);
            if(rb.getCode()==200 && type==2){
                model.addAttribute("msg","申请挂失中，请静待2~3个工作日会有短信通知您，如有问题请联系管理员\n管理员电话：133xxxxxxxx");
            }else if(rb.getCode()==200 && type==4){
                model.addAttribute("msg","申请冻结中，请静待2~3个工作日会有短信通知您，如有问题请联系管理员\n管理员电话：133xxxxxxxx");
            }else if(rb.getCode()==200 && type==6){
                model.addAttribute("msg","申请注销中，请静待2~3个工作日会有短信通知您，如有问题请联系管理员\n管理员电话：133xxxxxxxx");
            }else if(rb.getCode()==500){
                model.addAttribute("msg","页面丢失请稍后再试或联系管理员\n管理员电话：133xxxxxxxx");
            }
        }else {
            model.addAttribute("msg","当前信用卡状态为："+ccmsCredit.getStatus()+"，无法执行此操作");
        }
        return "active3";
    }

    //根据登录账户查询该账户下所有信用卡
    @ApiOperation(value = "根据登录账户查询该账户下所有信用卡")
    @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "Long")
    @GetMapping(value = "/myAllCredit")
//    @RequestMapping("/myAllCredit")
    public String getAllCreditByUserId(Long cardnum, Model model, HttpServletRequest request){
        Integer userId = Integer.valueOf((String)request.getSession().getAttribute("userid"));
        List<CcmsCredit> myCredits = iCredit.getMyCredit(userId);
        CcmsCredit ccmsCredit = null;
        if (cardnum == null){
            ccmsCredit = myCredits.get(0);
        }else {
            ccmsCredit = iCredit.getCredit(cardnum,request);
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");//设置日期格式
        String format = df.format(new Date());// new Date()为获取当前系统时间
        ccmsCredit.setRepayment(format+"-"+ccmsCredit.getRepayment());
        model.addAttribute("ccmsCredit",ccmsCredit);
        model.addAttribute("myCredits",myCredits);
        return "user";
    }

    /**
     * 修改信用卡的密码
     * @param cardnum
     * @param oupwd
     * @param nupwd
     * @return
     */
    @ApiOperation(value = "修改信用卡的密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "oupwd",value = "旧密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "nupwd",value = "新密码",required = true,dataType = "String"),
    })
    @PostMapping(value = "/updatePwd")
//    @RequestMapping("/updatePwd")
    @ResponseBody
    public ResultBean updatePwd(long cardnum,String oupwd,String nupwd,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(cardnum,request);
        if(oupwd.equals(ccmsCredit.getCreditPwd())){
            ccmsCredit.setCreditPwd(nupwd);
            int s=iCredit.updatepwd(ccmsCredit);
            if(s>0){
                return new ResultBean<>(200,"修改密码成功");
            }else {
                return new ResultBean<>(500,"修改密码失败");
            }
        }else {
            return new ResultBean<>(500,"密码输入错误！！");
        }
    }

    @ApiOperation(value = "修改信用卡的额度")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "long"),
            @ApiImplicitParam(name = "limit",value = "额度",required = true,dataType = "BigDecimal"),
    })
    @PostMapping(value = "/uplimit")
//    @RequestMapping("/uplimit")
    @ResponseBody
    public ResultBean upLimit(long cardnum, BigDecimal limit, HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(cardnum,request);
        ccmsCredit.setCreditLimit(limit);
        int s=iCredit.updatepwd(ccmsCredit);
        if(s>0){
            return new ResultBean<>(200,"修改成功");
        }else {
            return new ResultBean<>(500,"修改失败");
        }

    }

    @ApiOperation(value = "跳转到修改状态(挂失。。)页面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "String"),
            @ApiImplicitParam(name = "identityId",value = "证件号",required = true,dataType = "String"),
            @ApiImplicitParam(name = "creditPwd",value = "信用卡密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "type",value = "状态",required = true,dataType = "int"),
    })
    @PostMapping(value = "/tgs1")
    //验证并跳转挂失页面
//    @RequestMapping("/tgs1")
    public String tgs1(String cardnum, String identityId,String creditPwd,int type,Model model,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(Long.valueOf(cardnum),request);
        TEssential ccmsUser=itEssential.getUser(identityId);
        if(ccmsCredit!=null && ccmsUser!=null) {
            if (ccmsCredit.getEssentialId() == ccmsUser.getEssentialid() && ccmsCredit.getCreditPwd().equals(creditPwd)) {
                UserCredit uc = new UserCredit(identityId, Long.valueOf(cardnum), ccmsUser.getRealname(), ccmsCredit.getActive(), ccmsCredit.getStatus());
                model.addAttribute("uc", uc);
                model.addAttribute("type", type);
                return "cardStatus";
            } else {
                return null;
            }
        }else {
            return null;
        }

    }

    @ApiOperation(value = "用AJAX异步时查询卡信息")
    @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "Long")
    @GetMapping(value = "/selectCard")
    @ResponseBody
//    @RequestMapping("/selectCard")
    //用AJAX异步时查询卡信息
    public ResultBean<CcmsCredit> selectCard(Long cardnum,HttpServletRequest request){
        CcmsCredit credit = iCredit.getCredit(cardnum, request);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");//设置日期格式
        String format = df.format(new Date());// new Date()为获取当前系统时间
        credit.setRepayment(format+"-"+credit.getRepayment());
        return new ResultBean<>(0,"查询成功!!!",credit);
    }

    @ResponseBody
    @RequestMapping("/updateRemindTime")
    //修改账号提醒时间
    public CcmsCredit updateRemindTime(String remindTime,HttpServletRequest request){
        return iCredit.updateRemindTime(remindTime,request);
    }


    /**
     * 跳转修改密码页面
     * @param cardnum
     * @param model
     * @return
     */
    @ApiOperation(value = "跳转修改密码页面")
    @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "String")
    @GetMapping(value = "/toudpwd")
//    @RequestMapping("/toudpwd")
    public String toudpwd(String cardnum,Model model){
        model.addAttribute("cardnum",cardnum);
        return "toudpwd";
    }


    /**
     * 跳转修改额度页面
     * @param cardnum
     * @param model
     * @return
     */
    @ApiOperation(value = "跳转修改额度页面")
    @ApiImplicitParam(name = "cardnum",value = "信用卡号",required = true,dataType = "String")
    @GetMapping(value = "/toudlimit")
//    @RequestMapping("/toudlimit")
    public String toudlimit(String cardnum,Model model,HttpServletRequest request){
        CcmsCredit ccmsCredit=iCredit.getCredit(Long.valueOf(cardnum),request);
        model.addAttribute("creditLimit",ccmsCredit.getCreditLimit());
        model.addAttribute("cardnum",cardnum);
        return "toudlimit";
    }
}
